package com.jrx.mservices.ribbon.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Rest模板配置类
 *
 * @author zwg
 * @create 2018-03-06 17:29
 */
@Configuration
public class RestTemplateCfg {

    /**
     * 配置加载RestTemplate实例， LoadBalanced注解开启均衡负载能力
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        //设置请求超时时间
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(3000);
        httpRequestFactory.setConnectTimeout(3000);
        httpRequestFactory.setReadTimeout(3000);

        return new RestTemplate();
    }

    /*
    可以通过如下代码 将参数配置化
    custom.rest.connection.connection-request-timeout=3000
    custom.rest.connection.connect-timeout=3000
    custom.rest.connection.read-timeout=3000

    @Bean
    @ConfigurationProperties(prefix = "custom.rest.connection")
    public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory();
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(customHttpRequestFactory());
    }
     */

}
